import sys
import os
from datetime import datetime
from enum import Enum

class LogLevel(Enum):
    """日志级别枚举"""
    DEBUG = 1
    INFO = 2
    WARNING = 3
    ERROR = 4
    CRITICAL = 5

class ColorCode:
    """ANSI颜色代码"""
    # 前景色
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    
    # 背景色
    BG_BLACK = '\033[40m'
    BG_RED = '\033[41m'
    BG_GREEN = '\033[42m'
    BG_YELLOW = '\033[43m'
    BG_BLUE = '\033[44m'
    BG_MAGENTA = '\033[45m'
    BG_CYAN = '\033[46m'
    BG_WHITE = '\033[47m'
    
    # 格式
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

class Logger:
    """支持颜色输出的日志系统"""
    
    # 日志级别对应的颜色
    LEVEL_COLORS = {
        LogLevel.DEBUG: ColorCode.CYAN,
        LogLevel.INFO: ColorCode.GREEN,
        LogLevel.WARNING: ColorCode.YELLOW,
        LogLevel.ERROR: ColorCode.RED,
        LogLevel.CRITICAL: ColorCode.MAGENTA + ColorCode.BOLD
    }
    
    # 日志级别对应的标签
    LEVEL_TAGS = {
        LogLevel.DEBUG: "DEBUG",
        LogLevel.INFO: "INFO",
        LogLevel.WARNING: "WARNING",
        LogLevel.ERROR: "ERROR",
        LogLevel.CRITICAL: "CRITICAL"
    }
    
    def __init__(self, name="Logger", min_level=LogLevel.INFO, use_color=True):
        """
        初始化日志记录器
        
        Args:
            name (str): 日志记录器名称
            min_level (LogLevel): 最小日志级别，低于此级别的日志不会被记录
            use_color (bool): 是否使用颜色输出
        """
        self.name = name
        self.min_level = min_level
        self.use_color = use_color and self._supports_color()
        
    def _supports_color(self):
        """
        检查终端是否支持颜色输出
        
        Returns:
            bool: 是否支持颜色输出
        """
        # Windows系统检查
        if os.name == 'nt':
            try:
                # 检查是否在Windows 10版本1511及以上
                import winreg
                with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 
                                  r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") as key:
                    build = int(winreg.QueryValueEx(key, "CurrentBuild")[0])
                    return build >= 10586
            except:
                return False
        
        # Unix系统检查
        return hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
    
    def _get_color(self, level):
        """
        获取指定日志级别的颜色代码
        
        Args:
            level (LogLevel): 日志级别
            
        Returns:
            str: 颜色代码
        """
        if not self.use_color:
            return ""
        return self.LEVEL_COLORS.get(level, "")
    
    def _format_message(self, level, message):
        """
        格式化日志消息
        
        Args:
            level (LogLevel): 日志级别
            message (str): 日志消息
            
        Returns:
            str: 格式化后的日志消息
        """
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        level_tag = self.LEVEL_TAGS.get(level, "UNKNOWN")
        color = self._get_color(level)
        reset = ColorCode.RESET if self.use_color else ""
        
        return f"{color}[{timestamp}] [{self.name}] [{level_tag}] {message}{reset}"
    
    def _should_log(self, level):
        """
        判断是否应该记录指定级别的日志
        
        Args:
            level (LogLevel): 日志级别
            
        Returns:
            bool: 是否应该记录
        """
        return level.value >= self.min_level.value
    
    def _log(self, level, message):
        """
        记录日志的核心方法
        
        Args:
            level (LogLevel): 日志级别
            message (str): 日志消息
        """
        if not self._should_log(level):
            return
            
        formatted_message = self._format_message(level, message)
        print(formatted_message, file=sys.stderr if level in [LogLevel.ERROR, LogLevel.CRITICAL] else sys.stdout)
    
    def debug(self, message):
        """记录DEBUG级别日志"""
        self._log(LogLevel.DEBUG, message)
    
    def info(self, message):
        """记录INFO级别日志"""
        self._log(LogLevel.INFO, message)
    
    def warning(self, message):
        """记录WARNING级别日志"""
        self._log(LogLevel.WARNING, message)
    
    def error(self, message):
        """记录ERROR级别日志"""
        self._log(LogLevel.ERROR, message)
    
    def critical(self, message):
        """记录CRITICAL级别日志"""
        self._log(LogLevel.CRITICAL, message)
    
    def set_level(self, level):
        """
        设置最小日志级别
        
        Args:
            level (LogLevel): 最小日志级别
        """
        self.min_level = level

# 创建全局日志记录器实例
default_logger = Logger("AI-Core")

# 便捷函数
def debug(message):
    default_logger.debug(message)

def info(message):
    default_logger.info(message)

def warning(message):
    default_logger.warning(message)

def error(message):
    default_logger.error(message)

def critical(message):
    default_logger.critical(message)